//
//  HomeViewController.m
//  ShanghaiShopping
//
//  Created by KDC on 2019/8/22.
//  Copyright © 2019 KDC. All rights reserved.
//

#import "HomeViewController.h"
#import "DiscoverTableViewCell.h"
#import "PublicRightImageCell.h"
#import "PublicThreeImageCell.h"
#import <SDCycleScrollView.h>
#import "DTHomeScrollView.h"
#import "HomeCenterScrollView.h"
#import "HomeBottomView.h"
#import "HomeBannerModel.h"
#import "HomeTopIconModel.h"
#import "HomeShopSHModel.h"
#import "HomeGLModel.h"
#import "WKWebViewController.h"

#import <CoreLocation/CoreLocation.h>
#import "ShanghaiNightsVC.h"
#import "OldViewController.h"
#import "VideoDetailViewController.h"
#import "LLSearchViewController.h"
#import "OldDetailViewController.h"
#import "KJBannerHeader.h"
#import "CustomCollectionViewCell.h"
#import "MPMoviePlayerVC.h"
#import "KJPlayerView.h"
#import "HSUpdateApp.h"

@interface HomeViewController () <UITableViewDelegate, UITableViewDataSource, SDCycleScrollViewDelegate, DTHomeScrollViewDelegate, CLLocationManagerDelegate, KJPlayerViewDelegate>

@property(nonatomic, strong) KJPlayerView *MPPlayer;
@property (nonatomic, strong) UIButton *btnPlay;//播放按钮
@property (nonatomic, strong) UIImageView *playbackgroundImage;//播放背景图
@property (nonatomic , strong) CLLocationManager *locManager;   ///<获得定位
/**
 得到当前位置
 */
@property (nonatomic , strong) CLLocation *currentLocation;

@property (nonatomic, strong) UITableView *tableView;
/**
 天气
 */
@property (nonatomic, strong) UIButton *weatherBtn;

@property (nonatomic, strong) SDCycleScrollView *sdcycleScrollView;//轮播图
@property (nonatomic, strong) DTHomeScrollView *topScrollView;
@property (nonatomic, strong) HomeCenterScrollView *centerScrollView;//卡片式轮播图
@property (nonatomic, strong) HomeBottomView *bottomView;//5个btn

@property (nonatomic, strong) UIView *tableHeaderView;

@property (nonatomic, strong) NSDictionary *dicData;
@property (nonatomic, strong) NSDictionary *shareDicData;
@property (nonatomic, strong) NSMutableArray *dataArr;

@property (nonatomic, strong) NSMutableArray *dataBannerArr;
@property (nonatomic, strong) NSMutableArray *dataBannerImagePathArr;

@property (nonatomic, strong) NSMutableArray *dataIconArr;
@property (nonatomic, strong) NSMutableArray *dataIconImageArr;
@property (nonatomic, strong) NSMutableArray *dataIconTitleArr;
@property (nonatomic, strong) NSMutableArray *dataIconLinkPathArr;

@property (nonatomic, strong) NSMutableArray *dataShopSHArr;//九月购上海
@property (nonatomic, strong) NSMutableArray *dataStrategyArr;//攻略
@property (nonatomic, strong) NSMutableArray *comeAcrossArr;//遇见上海（四个按钮）

@property (nonatomic, assign) NSInteger refreshCount;//上滑次数
@property (nonatomic, assign) NSInteger totalCount;//列表个数
/**
 视频URL
 */
@property (nonatomic, strong) NSString *videoPath;
/**
 视频背景图
 */
@property (nonatomic, strong) NSString *videoBgImgPath;

/**
 视频父视图
 */
@property (nonatomic, strong) UIView *playerSuperView;

@end

@implementation HomeViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addNav];
    [self initHomeUI];
    //申请用户授权
    [self.locManager requestWhenInUseAuthorization];
    [self.locManager startUpdatingLocation];    //开始更新当前位置信息
 
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didSelect:)
                                                 name:@"HomeCardContentViewIndex"
                                               object:nil];
//    App Store更新
    [self checkTheAppStoreUpdate];
}

- (void)didSelect:(NSNotification *)notification {
    
    NSInteger index = [notification.userInfo[@"index"] integerValue];
    HomeShopSHModel *model = self.dataShopSHArr[index];
    WKWebViewController *vc = [[WKWebViewController alloc] initWithURLString:model.linkPath];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - UI
- (void)initHomeUI {
    [self.view addSubview:self.tableView];
    
    // 添加头部的下拉刷新
    MJRefreshNormalHeader *header = [[MJRefreshNormalHeader alloc] init];
    [header setRefreshingTarget:self refreshingAction:@selector(headerClick)];
    self.tableView.mj_header = header;
    [header beginRefreshing];
    
    // 添加底部的上拉加载
    MJRefreshBackNormalFooter *footer = [[MJRefreshBackNormalFooter alloc] init];
    [footer setRefreshingTarget:self refreshingAction:@selector(footerClick)];
    self.tableView.mj_footer = footer;
    
    self.tableView.rowHeight = UITableViewAutomaticDimension; // 自适应xib高度
    self.tableView.estimatedRowHeight = 200; //先估计一个高度
}


// 头部的下拉刷新触发事件
- (void)headerClick {
    self.refreshCount = 1;
    [self loadNetData];
    // 结束刷新
    [self.tableView.mj_header endRefreshing];
}
// 底部的上拉加载触发事件
- (void)footerClick {
    self.refreshCount++;
    [self addData];
}

- (void)addNav {
    CGFloat navHeight = kNavBarAndStatusBarHeight + 30;
    UIView *navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, navHeight)];
    navView.backgroundColor = Color_APP;
    [self.view addSubview:navView];
    
    UILabel *lbCity = [[UILabel alloc] initWithFrame:CGRectMake(16, navHeight - 34 - 11, 50, 34)];
    lbCity.text = @"上海";
    lbCity.font = FONT_BOLD(24);
    lbCity.textColor = UIColor.whiteColor;
    [navView addSubview:lbCity];
    
    self.weatherBtn = [[UIButton alloc] initWithFrame:CGRectMake(GetViewXW(lbCity) + 5, lbCity.center.y - 16, 80, 32)];
    [self.weatherBtn addTarget:self action:@selector(actionWeather) forControlEvents:UIControlEventTouchUpInside];
    self.weatherBtn.contentMode = UIViewContentModeScaleAspectFit;
    self.weatherBtn.titleLabel.font = FONT(14);
//    [self.weatherBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
    [navView addSubview:self.weatherBtn];
    
    UIButton *btnSearch = [[UIButton alloc] initWithFrame:CGRectMake(GetViewXW(self.weatherBtn) + 10, lbCity.center.y - 17, SCREEN_WIDTH - 16 - (GetViewXW(self.weatherBtn) + 12), 35)];
    [btnSearch addTarget:self action:@selector(actionSearch) forControlEvents:UIControlEventTouchUpInside];
    [btnSearch setTitle:@"  去哪购物" forState:UIControlStateNormal];
    [btnSearch setTitleColor:UIColorFromRGB(0xCCCCCC) forState:UIControlStateNormal];
    btnSearch.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    btnSearch.titleLabel.font = FONT_BOLD(15);
    btnSearch.backgroundColor = RGBCOLOR(245, 245, 245);
    btnSearch.layer.cornerRadius = 17;
    btnSearch.layer.masksToBounds = YES;
    [navView addSubview:btnSearch];
    
    UIImageView *searchImage = [[UIImageView alloc] initWithFrame:CGRectMake(btnSearch.frame.size.width - 21 - 15, 7, 21, 21)];
    searchImage.image = ImageNamed(@"Home_Search");
    [btnSearch addSubview:searchImage];
}

- (void)actionWeather {
    WKWebViewController *vc = [[WKWebViewController alloc] initWithURLString:@"https://m.baidu.com/sf?top=%7B%22sfhs%22%3A1%7D&pd=life_compare_weather&openapi=1&dspName=iphone&from_sf=1&word=%E4%B8%8A%E6%B5%B7%E5%A4%A9%E6%B0%94&title=VR%E5%A4%A9%E6%B0%94&resource_id=4774&current_city=%E4%B8%8A%E6%B5%B7&lid=11842950576173210013&referlid=11842950576173210013&ms=1&frsrcid=5063&frorder=1"];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - 网络请求
- (void)loadNetData {
    [SXLoadingView showProgressHUD:nil];
    if (self.dataStrategyArr.count != 0) {
        [self.dataStrategyArr removeAllObjects];
    }

    [PPNetworkHelper POST:URL_getIndexInit parameters:nil responseCache:^(id responseCache) {

    } success:^(id responseObject) {
        [SXLoadingView hideProgressHUD];
        
        self.dicData = responseObject[@"retBody"];
        [self setHomeUIData];
        self.tableView.tableHeaderView = self.tableHeaderView;
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:SXLoadingErrorStr duration:SXLoadingTime];
    }];
}

- (void)setHomeUIData {
//天气图片
    [self.weatherBtn setImage:ImageNamed(@"NEW") forState:UIControlStateNormal];
    [self.weatherBtn setTitle:[NSString stringWithFormat:@"  %@℃", DSStringValue(self.dicData[@"weather"][@"wendu"])] forState:UIControlStateNormal];
//获取当前时间日期
    NSDate *date = [NSDate date];
    NSDateFormatter *format1 = [[NSDateFormatter alloc] init];
    [format1 setDateFormat:@"MM"];
    NSString *month = [format1 stringFromDate:date];
    NSInteger monthInt = month.integerValue;
    switch (monthInt) {
        case 1:
            month = @"一";
            break;
        case 2:
            month = @"二";
            break;
        case 3:
            month = @"三";
            break;
        case 4:
            month = @"四";
            break;
        case 5:
            month = @"五";
            break;
        case 6:
            month = @"六";
            break;
        case 7:
            month = @"七";
            break;
        case 8:
            month = @"八";
            break;
        case 9:
            month = @"九";
            break;
        case 10:
            month = @"十";
            break;
        case 11:
            month = @"十一";
            break;
        case 12:
            month = @"十二";
            break;
        default:
            month = @"";
            break;
    }
    //SdcycleScrollView
    {
        if (self.dataBannerImagePathArr != 0) {
            [self.dataBannerImagePathArr removeAllObjects];
        }
        self.dataBannerArr = [HomeBannerModel arrayOfModelsFromDictionaries:self.dicData[@"banner"] error:nil];
        [self.dataBannerImagePathArr addObject:@""];
        
        for (int i = 0; i < self.dataBannerArr.count; i++) {
            HomeBannerModel *model = self.dataBannerArr[i];
            
            if ([model.type isEqualToString:@"4"]) {
                self.videoPath = [NSString stringWithFormat:@"%@", DSStringValue(model.videoPath)];
                self.videoBgImgPath = [NSString stringWithFormat:@"%@", DSStringValue(model.videoBgImgPath)];
                
                [self.playbackgroundImage sd_setImageWithURL:[NSURL URLWithString:self.videoBgImgPath] placeholderImage:LHYPlaceholderImage];
            }
            NSString *imagePath = [NSString stringWithFormat:@"%@",DSStringValue(model.imgPath)];
            if (!IsNilString(imagePath)) {
                [self.dataBannerImagePathArr addObject:model.imgPath];
            }
        }
        self.sdcycleScrollView.imageURLStringsGroup = self.dataBannerImagePathArr;
    }
    //九宫格
    {
        self.dataIconArr = [HomeTopIconModel arrayOfModelsFromDictionaries:self.dicData[@"icon"] error:nil];
        
        
        self.dataIconImageArr = [[NSMutableArray alloc] init];
        self.dataIconTitleArr = [[NSMutableArray alloc] init];
        self.dataIconLinkPathArr = [[NSMutableArray alloc] init];
        
        for (int i = 0; i < self.dataIconArr.count; i++) {
            HomeTopIconModel *model = self.dataIconArr[i];
            [self.dataIconImageArr addObject:DSStringValue(model.imgPath)];
            [self.dataIconTitleArr addObject:DSStringValue(model.name)];
            [self.dataIconLinkPathArr addObject:DSStringValue(model.linkPath)];
        }
    }
    {
        [self.dataStrategyArr addObjectsFromArray:self.dicData[@"gl"]];//tableview data
    }
    {
        [self.comeAcrossArr addObjectsFromArray:self.dicData[@"comeAcross"]];
        [self.bottomView updateUIWith:self.comeAcrossArr];
    }
    {
        self.dataShopSHArr = [HomeShopSHModel arrayOfModelsFromDictionaries:self.dicData[@"shopSH"] error:nil];
        [self.centerScrollView updateUIWith:self.dataShopSHArr title:[month stringByAppendingString:@"月购上海"]];
    }
}

#pragma mark - UI首页
- (UIView *)tableHeaderView {
    if (!_tableHeaderView) {
        _tableHeaderView = [[UIView alloc] init];
        [_tableHeaderView addSubview:self.sdcycleScrollView];
//        [_tableHeaderView addSubview:self.topScrollView];
        [_tableHeaderView addSubview:self.centerScrollView];
        [_tableHeaderView addSubview:self.bottomView];
        
        _tableHeaderView.frame = CGRectMake(0, 0, SCREEN_WIDTH, GetViewYH(self.bottomView));
    }
    return _tableHeaderView;
}

- (void)addData {
    NSDictionary *par = @{@"page":@(self.refreshCount),
                          @"pageSize":@"5"};
    [PPNetworkHelper POST:URL_getIndexNext parameters:par success:^(id responseObject) {
        NSArray *arr = responseObject[@"retBody"][@"rows"];
        
        self.totalCount = [responseObject[@"retBody"][@"total"] integerValue];
        if (IsNotNilArr(arr)) {
            [self.dataStrategyArr addObjectsFromArray:responseObject[@"retBody"][@"rows"]];
            [self.tableView reloadData];
        }
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:SXLoadingErrorStr duration:SXLoadingTime];
    }];
}

#pragma mark -- 九宫格按钮点击事件
- (void)buttonUpInsideWithView:(UIButton *)btn withIndex:(NSInteger)index withView:(DTHomeScrollView *)view {
    
    HomeTopIconModel *model = self.dataIconArr[index];
    //    1H5  2小程序  3原生  4其他app
    NSInteger type = [model.type integerValue];

    NSString *URLStr = [NSString stringWithFormat:@"%@", DSStringValue(model.linkPath)];
    
    switch (type) {
            case 1: {//1H5
                if (model.appJumpPath.integerValue == 5 || model.appJumpPath.integerValue == 7) {//“商圈商街”和“首店专线”需要传参，经纬度
                    CGFloat latitude = self.currentLocation.coordinate.latitude;
                    CGFloat longitude = self.currentLocation.coordinate.longitude;
                    
                    NSString *getCoordinate;
                    if (longitude == 0 && latitude == 0) {
                        getCoordinate = @"#/?getCoordinate=0.0,0.0";
                    } else {
                        getCoordinate = [NSString stringWithFormat:@"#/?getCoordinate=%f,%f",latitude, longitude];
                    }
                    URLStr = [URLStr stringByAppendingString:getCoordinate];
                }
                
                WKWebViewController *vc = [[WKWebViewController alloc] initWithURLString:URLStr];
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
            case 2: {//2小程序
                if ([WXApi isWXAppInstalled]) {
                    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
                    launchMiniProgramReq.userName = [NSString stringWithFormat:@"%@", model.appId];  //拉起的小程序的username-原始ID
                    launchMiniProgramReq.path = [NSString stringWithFormat:@"%@", model.appPath];    //拉起小程序页面的可带参路径，不填默认拉起小程序首页
                    launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型 正式版
//                    WXMiniProgramTypeRelease
//                    WXMiniProgramTypeTest
//                    WXMiniProgramTypePreview
                    [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
                        
                    }];
                } else {
                    [SXLoadingView showAlertHUD:@"您还未安装微信~请先下载安装哦" duration:SXLoadingTime];
                }
            }
            break;
            case 3: {//3原生
                
            }
            break;
            case 4: {//4其他app
                
            }
            break;
            
        default:
            break;
    }
    
    
    switch ([model.appJumpPath integerValue]) {
        case 2:{
            ShanghaiNightsVC *vc = [[ShanghaiNightsVC alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 3:{
            OldViewController *vc = [[OldViewController alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 16: {
            // 1.获取application对象
            UIApplication *app = [UIApplication sharedApplication];
            // 2.创建要打开的应用程序的URL
            NSURL *url = [NSURL URLWithString:@"metro://qrcode"];
            // 3.判断是否可以打开另一个应用
            if ([app canOpenURL:url]) {
                // 能，就打开
                [app openURL:url options:@{} completionHandler:nil];
            } else {
                NSLog(@"打开应用失败，跳转App Store");
                NSString *str = [@"https://apps.apple.com/cn/app/metro大都会/id1202750238" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
                NSURL *url = [NSURL URLWithString:str];
                [app openURL:url options:@{} completionHandler:nil];
            }
        }
            break;
            
        default:{
            
        }
            break;
    }
}

#pragma mark --UITableView代理

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    [tableView tableViewDisplayWitMsg:@"请下拉加载" ifNecessaryForRowCount:self.dataStrategyArr.count image:@""];
    
    //刷新数据处理
    self.tableView.mj_footer.hidden = (self.dataStrategyArr.count == 0);
    if (self.dataStrategyArr.count == self.totalCount) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
    
    return self.dataStrategyArr.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    NSDictionary *dicData = self.dataStrategyArr[indexPath.row];
    /**
     1一张图 2三张图 3视频
     */
    NSInteger cssType = [dicData[@"cssType"] integerValue];
    if (cssType == 3) {
        MPMoviePlayerVC *vc = [[MPMoviePlayerVC alloc] init];
        vc.videoTitle = dicData[@"title"];
        vc.videoPath = dicData[@"videoPath"];
        vc.fromName = dicData[@"fromName"];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        if (!IsNilString(dicData[@"linkPath"])) {
            WKWebViewController *webVC = [[WKWebViewController alloc] initWithURLString:dicData[@"linkPath"]];
            webVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:webVC animated:YES];
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = CellID_DiscoverTableViewCell;
    DiscoverTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[DiscoverTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    return cell;
}
//在willDisplayCell里面处理数据能优化tableview的滑动流畅性
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    DiscoverTableViewCell *disCell = (DiscoverTableViewCell *)cell;
    [disCell.shareBtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    disCell.shareBtn.tag = indexPath.row + 1000;
    if (IsNotNilArr(self.dataStrategyArr)) {
        NSDictionary *dicData = self.dataStrategyArr[indexPath.row];
        [disCell updateDiscoverTableViewCellWithdata:dicData];
    }
}
#pragma mark - 一行代码实现检测app是否为最新版本
- (void)checkTheAppStoreUpdate {
    /**
     一行代码实现检测app是否为最新版本。appId，bundelId，随便传一个 或者都传nil 即可实现检测。
     @param currentVersion 返回当前版本号
     @param storeVersion 返回商店版本号
     @param openUrl 跳转到商店下载的链接
     @param isUpdate 是否需要更新
     @return
     */
    [HSUpdateApp hs_updateWithAPPID:AppID withBundleId:nil block:^(NSString *currentVersion, NSString *storeVersion, NSString *openUrl, BOOL isUpdate) {
        
        if (isUpdate) {
            [self showAlertViewTitle:@"App Store版本更新" subTitle:[NSString stringWithFormat:@"%@，推荐立即更新哦~", storeVersion] openUrl:openUrl];
        } else {
            NSLog(@"当前板本%@，App Store版本%@，不需要更新", currentVersion, storeVersion);
        }
    }];
}

- (void)showAlertViewTitle:(NSString *)title subTitle:(NSString *)subTitle openUrl:(NSString *)openUrl {
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:subTitle preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([[UIApplication sharedApplication] respondsToSelector:@selector(openURL:options:completionHandler:)]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl] options:@{} completionHandler:^(BOOL success) {
                
            }];
        }
    }];
    [alertVC addAction:cancel];
    [alertVC addAction:sure];
    [self presentViewController:alertVC animated:YES completion:nil];
}
#pragma mark - 友盟分享
- (void)shareAction:(UIButton *)sender {
    self.shareDicData = self.dataStrategyArr[sender.tag - 1000];
    
    [self shareAlertView];
//    友盟原生UI面板
    {
//        [UMSocialUIManager setPreDefinePlatforms:@[
//                                                   @(UMSocialPlatformType_QQ),
//                                                   @(UMSocialPlatformType_WechatSession),
//                                                   @(UMSocialPlatformType_UserDefine_Begin + 1)]];
//        [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
//            // 根据获取的platformType确定所选平台进行下一步操作
//            [self shareWebPageToPlatformType:platformType dic:dic];
//        }];
    }
}

- (void)shareAlertView {
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    //    蒙板
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    view.tag = 9998;
    view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
    [window addSubview:view];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRemoveShareView:)];
    [view addGestureRecognizer:tap];
  
    
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(16, SCREEN_HEIGHT - 120 - 28, SCREEN_WIDTH - 32, 120)];
    whiteView.backgroundColor = [UIColor whiteColor];
    whiteView.tag = 9999;
    ViewBorderRadius(whiteView, 10, 0, [UIColor whiteColor]);
    [window addSubview:whiteView];

    //间距
    float weight = 65;
    int range = (whiteView.frame.size.width - weight * 4) / 5;
    NSArray *arr = @[@"微信",
                     @"朋友圈",
                     @"QQ"];
    
    for (int i = 0; i < arr.count; i++) {
        UIButton *imageBtn = [[UIButton alloc] initWithFrame:CGRectMake(range + i * (weight + range), 20, weight, weight)];
        [imageBtn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"分享%d", i]] forState:UIControlStateNormal];
//        if (i == 3) {
//            if ([self.shareDicData[@""] integerValue] == 1) {
//                [imageBtn setImage:ImageNamed(@"分享3_Y") forState:UIControlStateNormal];
//            }
//        }
        [imageBtn addTarget:self action:@selector(shareBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        imageBtn.tag = i + 10000;
        [imageBtn setTitle:arr[i] forState:UIControlStateNormal];
        [whiteView addSubview:imageBtn];
        
        UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(range + i * (weight + range), GetViewYH(imageBtn), weight, 17)];
        lb.tag = i + 10010;
        lb.textColor = UIColorFromRGB(0x333333);
        lb.font = FONT(12);
        lb.text = arr[i];
        lb.textAlignment = 1;
        [whiteView addSubview:lb];
    }
//    if (![QQApiInterface isQQInstalled]) {//没有安装QQ
//        UIButton *btn = [whiteView viewWithTag:10002];
//        btn.hidden = YES;
//
//        UILabel *lb = [whiteView viewWithTag:10012];
//        lb.hidden = YES;
//    }
//    if (![WXApi isWXAppInstalled]) { //没有安装微信
//        UIButton *btn0 = [whiteView viewWithTag:10000];
//        UIButton *btn1 = [whiteView viewWithTag:10001];
//        btn0.hidden = YES;
//        btn1.hidden = YES;
//
//        UILabel *lb0 = [whiteView viewWithTag:10010];
//        UILabel *lb1 = [whiteView viewWithTag:10011];
//        lb0.hidden = YES;
//        lb1.hidden = YES;
//    }
}

- (void)shareBtnAction:(UIButton *)sender {
    [self removeShareView];
    NSInteger platformType = 0;
    switch (sender.tag) {
        case 10000: {
            platformType = 1;//微信聊天
        }
            break;
        case 10001: {
            platformType = 2;//微信朋友圈
        }
            break;
        case 10002: {
            platformType = 4;//QQ聊天
        }
            break;
        case 10003: {
  
            if ([UserManager sharedUserManager].isLogin) {
                NSString *str = [NSString stringWithFormat:@"%@", DSStringValue(self.shareDicData[@"id"])];
                NSDictionary *par = @{@"userId":DSStringValue([UserManager sharedUserManager].userInfo.uid),
                                      @"tweetId":str
                                      };
                
                [PPNetworkHelper POST:URL_addCollect parameters:par success:^(id responseObject) {
                    [SXLoadingView showAlertHUD:responseObject[@"retMsg"] duration:SXLoadingTime];
                } failure:^(NSError *error) {
                    [SXLoadingView showAlertHUD:SXLoadingErrorStr duration:SXLoadingTime];
                }];
            } else {
                LoginAndRegisterVC *vc = [[LoginAndRegisterVC alloc] init];
                vc.hidesBottomBarWhenPushed = YES;
                vc.pushType = 1;
                [self.navigationController pushViewController:vc animated:YES];
            }
            return;
        }
            break;
            
        default:
            break;
    }
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //创建网页内容对象
    NSString *thumbURL =  self.shareDicData[@"imgPath"];
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.shareDicData[@"fromName"] descr:self.shareDicData[@"title"] thumImage:thumbURL];
    //设置网页地址
    shareObject.webpageUrl = self.shareDicData[@"linkPath"];
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************分享失败 %@*********",error);
        } else {
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"响应消息 %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"原始响应数据 %@",resp.originalResponse);
            } else {
                UMSocialLogInfo(@"响应数据 %@",data);
            }
        }
    }];
}

- (void)tapRemoveShareView:(UITapGestureRecognizer *)tap {
    [self removeShareView];
}

- (void)removeShareView {
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    UIView *view0 = [window viewWithTag:9998];
    UIView *view1 = [window viewWithTag:9999];
    
    [view0 removeFromSuperview];
    [view1 removeFromSuperview];
}
#pragma mark - 点击事件
- (void)actionSearch {
    LLSearchViewController *searchVC = [[LLSearchViewController alloc] init];
    searchVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchVC animated:YES];
}

- (void)actionPlay {
    if ([PPNetworkHelper isWiFiNetwork]) {//实时网络
        [self canPlay];
    } else {
        if ([UserDefaults boolForKey:UserDefaultsPlayInAllNet]) {//沙盒网络
            [self canPlay];
        } else {
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"您当前正在使用移动网络,\n继续播放将消耗流量" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction * photo = [UIAlertAction actionWithTitle:@"继续播放" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self canPlay];
                [UserDefaults setBool:YES forKey:UserDefaultsPlayInAllNet];
                [UserDefaults synchronize];
            }];
            UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"停止播放" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            //添加各个按钮事件
            [alert addAction:photo];
            [alert addAction:cancel];
            //弹出sheet提示框
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
}

- (void)canPlay {
    self.btnPlay.hidden = YES;
    self.playbackgroundImage.hidden = YES;
//    NSString *url = @"https://mp4.vjshi.com/2017-07-02/0cbbf21c6003f7936f4086dd10e7ebf5.mp4";
    NSString *url = DSStringValue(self.videoPath);
    [_MPPlayer kj_setPlayWithURL:url StartTime:0];
}


#pragma mark -  /** SDCycleScrollView 代理 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    if (index == 0) {//视频不予处理
        
    } else {
        HomeBannerModel *model = self.dataBannerArr[index - 1];
        NSInteger type = [model.type integerValue];
        
        switch (type) {
            case 1:{//图
                
            }
                break;
            case 2:{//推文
                WKWebViewController *webVC = [[WKWebViewController alloc] initWithURLString:[NSString stringWithFormat:@"%@", model.linkPath]];
                webVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:webVC animated:YES];
            }
                break;
            case 3:{//小程序
                if ([WXApi isWXAppInstalled]) {
                    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
                    launchMiniProgramReq.userName = [NSString stringWithFormat:@"%@", model.appId];  //拉起的小程序的username-原始ID
                    launchMiniProgramReq.path = [NSString stringWithFormat:@"%@", model.appPath];    //拉起小程序页面的可带参路径，不填默认拉起小程序首页
                    launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
                    [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
                        
                    }];
                } else {
                    [SXLoadingView showAlertHUD:@"您还未安装微信~请先下载安装哦" duration:SXLoadingTime];
                }
            }
                break;
                
            default:
                break;
        }
    }
}
// 不需要自定义轮播cell的请忽略下面的代理方法
// 如果要实现自定义cell的轮播图，必须先实现customCollectionViewCellClassForCycleScrollView:和setupCustomCell:forIndex:代理方法
- (Class)customCollectionViewCellClassForCycleScrollView:(SDCycleScrollView *)view {
    if (view != _sdcycleScrollView) {
        return nil;
    }
    return [CustomCollectionViewCell class];
}

- (void)setupCustomCell:(UICollectionViewCell *)cell forIndex:(NSInteger)index cycleScrollView:(SDCycleScrollView *)view {
    
    CustomCollectionViewCell *myCell = (CustomCollectionViewCell *)cell;
    [myCell.imageView sd_setImageWithURL:[NSURL URLWithString:self.dataBannerImagePathArr[index]] placeholderImage:LHYPlaceholderImage];
    
    if (index == 0) {
        self.playerSuperView = myCell.contentView;
        [myCell.contentView addSubview:self.MPPlayer];
        [self.MPPlayer addSubview:self.playbackgroundImage];
        [self.MPPlayer addSubview:self.btnPlay];
    }
}
 
#pragma mark - 地图定位 delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    //得到当前位置
    CLLocation *currentLocation = locations.lastObject;
    self.currentLocation = currentLocation;
}

#pragma mark - Setter Getter 方法
- (UIButton *)btnPlay {
    if (!_btnPlay) {
        _btnPlay = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 54, 54)];
        _btnPlay.center = self.MPPlayer.center;
        [_btnPlay setImage:ImageNamed(@"播放 copy") forState:UIControlStateNormal];
        [_btnPlay addTarget:self action:@selector(actionPlay) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnPlay;
}

- (UIImageView *)playbackgroundImage {
    if (!_playbackgroundImage) {
        _playbackgroundImage = [[UIImageView alloc] initWithFrame:self.sdcycleScrollView.bounds];
    }
    return _playbackgroundImage;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight + 30, SCREEN_WIDTH, SCREEN_HEIGHT - (kNavBarAndStatusBarHeight + 30) - kTabBarHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"DiscoverTableViewCell" bundle:nil] forCellReuseIdentifier:CellID_DiscoverTableViewCell];
        [_tableView registerNib:[UINib nibWithNibName:@"PublicRightImageCell" bundle:nil] forCellReuseIdentifier:CellID_PublicRightImageCell];
        [_tableView registerNib:[UINib nibWithNibName:@"PublicThreeImageCell" bundle:nil] forCellReuseIdentifier:CellID_PublicThreeImageCell];
    }
    return _tableView;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}

- (SDCycleScrollView *)sdcycleScrollView {
    if (!_sdcycleScrollView) {
        _sdcycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(16, 16, SCREEN_WIDTH - 32, (SCREEN_WIDTH - 32) * VideoScale) shouldInfiniteLoop:YES imageNamesGroup:nil];
        _sdcycleScrollView.layer.cornerRadius = 10;
        _sdcycleScrollView.layer.masksToBounds = YES;
        _sdcycleScrollView.delegate = self;
        _sdcycleScrollView.showPageControl = YES;
        _sdcycleScrollView.autoScrollTimeInterval = 30;
    }
    return _sdcycleScrollView;
}

- (DTHomeScrollView *)topScrollView {
    if (!_topScrollView) {
        NSMutableArray *views = [NSMutableArray array];
        for (int i = 0; i < self.dataIconTitleArr.count; i++) {
            DTHomeButton *btn = [[DTHomeButton alloc] initWithFrame:CGRectZero withTitle:self.dataIconTitleArr[i] withImageURLString:self.dataIconImageArr[i]];
            [btn.btnTitle setTextColor:UIColorFromRGB(0x333333)];
            [views addObject:btn];
        }
        _topScrollView = [[DTHomeScrollView alloc] initWithFrame:CGRectMake(0, GetViewYH(self.sdcycleScrollView), SCREEN_WIDTH, 204 + 24) viewsArray:views];
        _topScrollView.delegate = self;
    }
    return _topScrollView;
}
#pragma mark - 九月购上海
- (HomeCenterScrollView *)centerScrollView {
    if (!_centerScrollView) {
        _centerScrollView = [[HomeCenterScrollView alloc] initWithFrame:CGRectMake(0, GetViewYH(self.sdcycleScrollView), SCREEN_WIDTH, 333)];
        WeakSelf;
        _centerScrollView.block = ^(NSInteger type, NSString * _Nonnull linkPath, NSString * _Nonnull appId, NSString * _Nonnull appPath) {
            StrongSelf;
            //type  1图 2推文 3小程序 4原生app
            switch (type) {
                    case 1: {
                        
                    }
                    break;
                    case 2: {
                        WKWebViewController *webVC = [[WKWebViewController alloc] initWithURLString:linkPath];
                        webVC.hidesBottomBarWhenPushed = YES;
                        [strongSelf.navigationController pushViewController:webVC animated:YES];
                    }
                    break;
                    case 3: {
                        if ([WXApi isWXAppInstalled]) {
                            WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
                            launchMiniProgramReq.userName = appId;  //拉起的小程序的username-原始ID
                            launchMiniProgramReq.path = appPath;    //拉起小程序页面的可带参路径，不填默认拉起小程序首页
                            launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
                            [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
                                
                            }];
                        } else {
                            [SXLoadingView showAlertHUD:@"您还未安装微信~请先下载安装哦" duration:SXLoadingTime];
                        }
                    }
                    break;
                    case 4: {
                        
                    }
                    break;
                    
                default:
                    break;
            }
        };
    }
    return _centerScrollView;
}

#pragma mark - 遇见上海 四个按钮
- (HomeBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[HomeBottomView alloc] initWithFrame:CGRectMake(0, GetViewYH(self.centerScrollView), SCREEN_WIDTH, 325)];
        WeakSelf;
        _bottomView.bottomBtnClickBlock = ^(NSString * _Nonnull comeAcrossId) {
            StrongSelf;
            
            
            OldDetailViewController *vc = [[OldDetailViewController alloc] init];
            vc.comeAcrossId = comeAcrossId;
            vc.hidesBottomBarWhenPushed = YES;
            [strongSelf.navigationController pushViewController:vc animated:YES];
        };
    }
    return _bottomView;
}

- (NSMutableArray *)dataBannerImagePathArr {
    if (!_dataBannerImagePathArr) {
        _dataBannerImagePathArr = [[NSMutableArray alloc] init];
    }
    return _dataBannerImagePathArr;
}

- (NSMutableArray *)dataStrategyArr {
    if (!_dataStrategyArr) {
        _dataStrategyArr = [[NSMutableArray alloc] init];
    }
    return _dataStrategyArr;
}

- (NSMutableArray *)dataShopSHArr {
    if (!_dataShopSHArr) {
        _dataShopSHArr = [[NSMutableArray alloc] init];
    }
    return _dataShopSHArr;
}

- (NSMutableArray *)comeAcrossArr {
    if (!_comeAcrossArr) {
        _comeAcrossArr = [[NSMutableArray alloc] init];
    }
    return _comeAcrossArr;
}

///重写 getter
- (CLLocationManager *)locManager {
    if (!_locManager) {
        _locManager = [[CLLocationManager alloc] init];
        _locManager.activityType = CLActivityTypeFitness; //步行导航
        _locManager.delegate = self;
        _locManager.distanceFilter = 1000.0f;//设置距离筛选器
    }
    return _locManager;
}
#pragma mark - 视频播放器
- (KJPlayerView *)MPPlayer {
    if (!_MPPlayer) {
        KJPlayerViewConfiguration *configuration = [[KJPlayerViewConfiguration alloc] init];
        configuration.autoHideTime = 5;
        configuration.playType = KJPlayerPlayTypeOnce;
        configuration.openGravitySensing = NO;//关闭重力感应横屏

        _MPPlayer = [[KJPlayerView alloc] initWithFrame:self.sdcycleScrollView.bounds Configuration:configuration];
        _MPPlayer.backgroundColor = UIColor.blackColor;
        _MPPlayer.delegate = self;
        _MPPlayer.playerSuperView = self.playerSuperView;
    }
    return _MPPlayer;
}

- (NSDictionary *)dicData {
    if (!_dicData) {
        _dicData = [[NSDictionary alloc] init];
    }
    return _dicData;
}

@end
